package cn.org.gs.channel;

import org.junit.Test;

import java.awt.image.BufferedImage;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class DataGramChannelDemo {

    @Test
    public void sendDataGram() throws Exception{
        // 打开DataGramChannel
        DatagramChannel sendChannel = DatagramChannel.open();

        InetSocketAddress sendAddress = new InetSocketAddress("127.0.0.1", 80);

        // 发送
        while (true){
            ByteBuffer buffer = ByteBuffer.wrap("你好，atguigu".getBytes("UTF-8"));
            sendChannel.send(buffer, sendAddress);
            System.out.println("发送完成了！");
        }
    }

    @Test
    public void receiveDataGram() throws Exception{
        DatagramChannel receiveChannel = DatagramChannel.open();
        InetSocketAddress receiveAddress = new InetSocketAddress(80);

        receiveChannel.bind(receiveAddress);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true){
            buffer.clear();
            SocketAddress sendAddress = receiveChannel.receive(buffer);
            buffer.flip();

            System.out.println(sendAddress.toString() + "");
            System.out.println(Charset.forName("UTF-8").decode(buffer));
        }
    }

    @Test
    public void testReadAndWrite() throws Exception{
        DatagramChannel connChannel = DatagramChannel.open();
        connChannel.bind(new InetSocketAddress(9999));

        connChannel.connect(new InetSocketAddress("127.0.0.1", 9999));
        connChannel.write(ByteBuffer.wrap("发送Data".getBytes("UTF-8")));
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);

        while (true) {
            readBuffer.clear();
            connChannel.read(readBuffer);
            readBuffer.flip();
            System.out.println(Charset.forName("UTF-8").decode(readBuffer));

        }
    }


}
